<template>
    <div class="workflow-page">
        <h1 class="page-title">工作流管理</h1>

        <!-- 筛选区域 -->
        <div class="filter-section">
            <div class="filter-header">
                <i class="filter-icon">⚙</i>
                <span>筛选</span>
            </div>
            <div class="filter-content">
                <el-input v-model="filterForm.doctorId" placeholder="医生ID" class="filter-input" />
                <el-select v-model="filterForm.status" placeholder="工作流状态" class="filter-select">
                    <el-option label="进行中" value="进行中" />
                    <el-option label="已完成" value="已完成" />
                    <el-option label="已拒绝" value="已拒绝" />
                </el-select>
                <el-button type="primary" @click="handleFilter" :loading="page.loading">筛选</el-button>
                <el-button @click="handleReset">重置</el-button>
                <el-button type="success" @click="openCreateWorkflowDialog">创建工作流</el-button>
            </div>
        </div>

        <!-- 工作流列表 -->
        <div class="workflow-list-section">
            <div class="list-header">
                <i class="list-icon">📋</i>
                <span>工作流列表</span>
                <span class="total-count">(共 {{ page.total }} 条数据)</span>
            </div>

            <el-table :data="workflowList" style="width: 100%" v-loading="page.loading" element-loading-text="加载中...">
                <el-table-column prop="id" label="工作流ID" width="100" />
                <el-table-column prop="doctorName" label="医生姓名" width="120" />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)" size="small">
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createdTime" label="创建时间" width="160">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.createdTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="completedTime" label="完成时间" width="160">
                    <template #default="scope">
                        {{ scope.row.completedTime ? formatDateTime(scope.row.completedTime) : '-' }}
                    </template>
                </el-table-column>
                <el-table-column prop="steps" label="步骤数" width="80">
                    <template #default="scope">
                        {{ scope.row.steps ? scope.row.steps.length : 0 }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button size="small" @click="viewWorkflowDetail(scope.row)">查看</el-button>
                        <el-button size="small" type="primary" @click="editWorkflowSteps(scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="table-footer">
                <div class="data-info">
                    <span>共{{ page.totalPages }}页/{{ page.total }}条数据</span>
                </div>
                <el-pagination v-model:current-page="page.currentPage" :page-size="page.pageSize" :total="page.total"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @current-change="handlePageChange" @size-change="handleSizeChange" />
            </div>
        </div>

        <!-- 工作流详情弹框 -->
        <el-dialog v-model="workflowDetailDialog.visible" title="工作流详情" width="800px">
            <div v-if="workflowDetailDialog.workflow" class="workflow-detail">
                <div class="detail-info">
                    <div class="info-item">
                        <label>工作流ID：</label>
                        <span>{{ workflowDetailDialog.workflow.id }}</span>
                    </div>
                    <div class="info-item">
                        <label>医生姓名：</label>
                        <span>{{ workflowDetailDialog.workflow.doctorName }}</span>
                    </div>
                    <div class="info-item">
                        <label>状态：</label>
                        <el-tag :type="getStatusType(workflowDetailDialog.workflow.status)">
                            {{ workflowDetailDialog.workflow.status }}
                        </el-tag>
                    </div>
                    <div class="info-item">
                        <label>创建时间：</label>
                        <span>{{ formatDateTime(workflowDetailDialog.workflow.createdTime) }}</span>
                    </div>
                    <div class="info-item" v-if="workflowDetailDialog.workflow.completedTime">
                        <label>完成时间：</label>
                        <span>{{ formatDateTime(workflowDetailDialog.workflow.completedTime) }}</span>
                    </div>
                </div>

                <div class="steps-section">
                    <h3>审核步骤</h3>
                    <div class="steps-list">
                        <div v-for="step in workflowDetailDialog.workflow.steps" :key="step.id" class="step-item">
                            <div class="step-header">
                                <span class="step-order">{{ step.stepOrder }}</span>
                                <span class="step-name">{{ step.serviceName }}</span>
                                <el-tag :type="getAuditStatusType(step.auditStatus)" size="small">
                                    {{ step.auditStatus }}
                                </el-tag>
                            </div>
                            <div class="step-content" v-if="step.auditTime">
                                <div class="step-info">
                                    <span>审核时间：{{ formatDateTime(step.auditTime) }}</span>
                                    <span v-if="step.auditor">审核人：{{ step.auditor }}</span>
                                </div>
                                <div class="step-remarks" v-if="step.remarks">
                                    <strong>备注：</strong>{{ step.remarks }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 创建工作流弹框 -->
        <el-dialog v-model="createWorkflowDialog.visible" title="创建工作流" width="600px">
            <div class="create-workflow-form">
                <el-form :model="createWorkflowDialog.form" label-width="100px">
                    <el-form-item label="医生ID">
                        <el-input v-model="createWorkflowDialog.form.doctorId" placeholder="请输入医生ID" />
                    </el-form-item>
                    <el-form-item label="服务类型">
                        <el-checkbox-group v-model="createWorkflowDialog.form.serviceTypeIds">
                            <el-checkbox v-for="serviceType in createWorkflowDialog.serviceTypes" :key="serviceType.id"
                                :label="serviceType.id">
                                {{ serviceType.name }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeCreateWorkflowDialog">取消</el-button>
                    <el-button type="primary" @click="submitCreateWorkflow" :loading="createWorkflowDialog.submitting">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 编辑工作流步骤弹框 -->
        <el-dialog v-model="editStepsDialog.visible" title="编辑工作流步骤" width="600px">
            <div class="edit-steps-content">
                <div v-for="step in editStepsDialog.steps" :key="step.id" class="edit-step">
                    <div class="step-header">
                        <h4 class="service-name">{{ step.serviceName }}</h4>
                    </div>
                    <div class="step-content">
                        <div class="audit-section">
                            <label class="audit-label">审核：</label>
                            <el-radio-group v-model="step.auditStatus" class="audit-options">
                                <el-radio label="审核通过">审核通过</el-radio>
                                <el-radio label="审核不通过">审核不通过</el-radio>
                            </el-radio-group>
                        </div>
                        <div class="remarks-section">
                            <label class="remarks-label">备注：</label>
                            <el-input v-model="step.remarks" type="textarea" :rows="3" placeholder="请输入" />
                        </div>
                    </div>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeEditStepsDialog">取消</el-button>
                    <el-button type="primary" @click="submitEditSteps" :loading="editStepsDialog.submitting">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { apiClient } from '@/api/doctor'

// 筛选表单
const filterForm = reactive({
    doctorId: '',
    status: ''
})

// 分页数据
const page = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0,
    loading: false
})

// 工作流列表数据
const workflowList = ref([])

// 工作流详情弹框
const workflowDetailDialog = reactive({
    visible: false,
    workflow: null as any
})

// 创建工作流弹框
const createWorkflowDialog = reactive({
    visible: false,
    submitting: false,
    form: {
        doctorId: '',
        serviceTypeIds: [] as number[]
    },
    serviceTypes: [] as any[]
})

// 编辑步骤弹框
const editStepsDialog = reactive({
    visible: false,
    submitting: false,
    workflowId: 0,
    steps: [] as any[]
})

// 获取工作流列表
const fetchWorkflowList = async () => {
    try {
        page.loading = true

        const queryParams: any = {
            pageIndex: page.currentPage,
            pageSize: page.pageSize
        }

        if (filterForm.doctorId) {
            queryParams.doctorId = parseInt(filterForm.doctorId)
        }
        if (filterForm.status) {
            queryParams.status = filterForm.status
        }

        const result = await apiClient.get('/api/WorkflowGetWorkflowList', {
            params: queryParams
        })

        if (result.data.code === 100) {
            workflowList.value = result.data.data.data
            page.total = result.data.data.totalCount
            page.totalPages = result.data.data.totalPages
        } else {
            ElMessage.error(result.data.message || '获取工作流列表失败')
        }
    } catch (error: any) {
        console.error('获取工作流列表失败:', error)
        ElMessage.error(error.message || '网络错误，请稍后重试')
    } finally {
        page.loading = false
    }
}

// 查看工作流详情
const viewWorkflowDetail = async (workflow: any) => {
    try {
        const result = await apiClient.get('/api/WorkflowGetWorkflowById', {
            params: {
                id: workflow.id
            }
        })
        if (result.data.code === 100) {
            workflowDetailDialog.workflow = result.data.data
            workflowDetailDialog.visible = true
        } else {
            ElMessage.error(result.data.message || '获取工作流详情失败')
        }
    } catch (error: any) {
        console.error('获取工作流详情失败:', error)
        ElMessage.error('获取工作流详情失败')
    }
}

// 编辑工作流步骤
const editWorkflowSteps = async (workflow: any) => {
    try {
        const result = await apiClient.put('/api/WorkflowGetWorkflowById', {
            params: {
                id: workflow.id
            }
        })
        if (result.data.code === 100) {
            editStepsDialog.workflowId = workflow.id
            editStepsDialog.steps = result.data.data.steps.map((step: any) => ({
                ...step,
                auditStatus: step.auditStatus || '',
                remarks: step.remarks || ''
            }))
            editStepsDialog.visible = true
        } else {
            ElMessage.error(result.data.message || '获取工作流详情失败')
        }
    } catch (error: any) {
        console.error('获取工作流详情失败:', error)
        ElMessage.error('获取工作流详情失败')
    }
}

// 打开创建工作流弹框
const openCreateWorkflowDialog = async () => {
    try {
        createWorkflowDialog.visible = true

        // 获取服务类型列表
        const result = await apiClient.get('/api/WorkflowGetServiceTypes')
        // const result = await workflowAPI.getServiceTypes()
        console.log(result.data);
        
        if (result.data.code === 100) {
            createWorkflowDialog.serviceTypes = result.data.data
        } else {
            ElMessage.error('获取服务类型失败')
        }
    } catch (error: any) {
        console.error('获取服务类型失败:', error)
        ElMessage.error('获取服务类型失败')
    }
}

// 关闭创建工作流弹框
const closeCreateWorkflowDialog = () => {
    createWorkflowDialog.visible = false
    createWorkflowDialog.form.doctorId = ''
    createWorkflowDialog.form.serviceTypeIds = []
}

// 提交创建工作流
const submitCreateWorkflow = async () => {
    try {
        if (!createWorkflowDialog.form.doctorId) {
            ElMessage.warning('请输入医生ID')
            return
        }
        if (createWorkflowDialog.form.serviceTypeIds.length === 0) {
            ElMessage.warning('请选择至少一个服务类型')
            return
        }

        createWorkflowDialog.submitting = true

        const result = await apiClient.post('/api/WorkflowCreateWorkflow', {
            doctorId: parseInt(createWorkflowDialog.form.doctorId),
            serviceTypeIds: createWorkflowDialog.form.serviceTypeIds
        })
        /* // const result = await workflowAPI .createWorkflow({
            doctorId: parseInt(createWorkflowDialog.form.doctorId),
            serviceTypeIds: createWorkflowDialog.form.serviceTypeIds
        })
 */
        if (result.data.code === 100) {
            ElMessage.success('工作流创建成功')
            closeCreateWorkflowDialog()
            fetchWorkflowList()
        } else {
            ElMessage.error(result.data.message || '工作流创建失败')
        }
    } catch (error: any) {
        console.error('创建工作流失败:', error)
        ElMessage.error('创建工作流失败')
    } finally {
        createWorkflowDialog.submitting = false
    }
}

// 关闭编辑步骤弹框
const closeEditStepsDialog = () => {
    editStepsDialog.visible = false
    editStepsDialog.steps = []
    editStepsDialog.workflowId = 0
}

// 提交编辑步骤
const submitEditSteps = async () => {
    try {
        editStepsDialog.submitting = true

        // 更新每个步骤
        for (const step of editStepsDialog.steps) {
            if (step.auditStatus) {
                await apiClient.put('/api/WorkflowUpdateWorkflowStep', {
                    stepId: step.id,
                    auditStatus: step.auditStatus,
                    remarks: step.remarks,
                    auditor: '审核员'
                })/* .updateWorkflowStep({
                    stepId: step.id,
                    auditStatus: step.auditStatus,
                    remarks: step.remarks,
                    auditor: '审核员'
                }) */
            }
        }

        ElMessage.success('工作流步骤更新成功')
        closeEditStepsDialog()
        fetchWorkflowList()
    } catch (error: any) {
        console.error('更新工作流步骤失败:', error)
        ElMessage.error('更新工作流步骤失败')
    } finally {
        editStepsDialog.submitting = false
    }
}

// 获取状态类型
const getStatusType = (status: string) => {
    switch (status) {
        case '进行中':
            return 'warning'
        case '已完成':
            return 'success'
        case '已拒绝':
            return 'danger'
        default:
            return 'info'
    }
}

// 获取审核状态类型
const getAuditStatusType = (status: string) => {
    switch (status) {
        case '审核通过':
            return 'success'
        case '审核不通过':
            return 'danger'
        case '未审核':
            return 'info'
        default:
            return 'info'
    }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
    if (!dateTimeStr) return ''
    const date = new Date(dateTimeStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    })
}

// 事件处理
const handleFilter = () => {
    page.currentPage = 1
    fetchWorkflowList()
}

const handleReset = () => {
    filterForm.doctorId = ''
    filterForm.status = ''
    page.currentPage = 1
    fetchWorkflowList()
}

const handlePageChange = (pages: number) => {
    page.currentPage = pages
    fetchWorkflowList()
}

const handleSizeChange = (size: number) => {
    page.pageSize = size
    page.currentPage = 1
    fetchWorkflowList()
}

// 组件挂载时获取数据
onMounted(() => {
    fetchWorkflowList()
})
</script>

<style scoped>
.workflow-page {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.page-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}

.filter-section,
.workflow-list-section {
    background: white;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-header,
.list-header {
    background: #f0f0f0;
    padding: 12px 16px;
    border-radius: 8px 8px 0 0;
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
    color: #666;
}

.total-count {
    margin-left: auto;
    font-size: 14px;
    color: #999;
}

.filter-content {
    padding: 20px;
    display: flex;
    gap: 16px;
    align-items: center;
    flex-wrap: wrap;
}

.filter-input,
.filter-select {
    width: 150px;
}

.workflow-list-section {
    padding-bottom: 0;
}

.table-footer {
    padding: 16px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #eee;
}

.data-info {
    color: #666;
    font-size: 14px;
}

/* 工作流详情样式 */
.workflow-detail {
    padding: 20px;
}

.detail-info {
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 6px;
}

.info-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.info-item:last-child {
    margin-bottom: 0;
}

.info-item label {
    font-weight: 500;
    color: #555;
    min-width: 100px;
}

.steps-section h3 {
    margin-bottom: 16px;
    color: #333;
}

.steps-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.step-item {
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 16px;
    background-color: #fafafa;
}

.step-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;
}

.step-order {
    background-color: #409eff;
    color: white;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: bold;
}

.step-name {
    font-weight: 600;
    color: #333;
}

.step-content {
    margin-top: 8px;
}

.step-info {
    display: flex;
    gap: 16px;
    margin-bottom: 8px;
    font-size: 14px;
    color: #666;
}

.step-remarks {
    font-size: 14px;
    color: #333;
}

/* 创建和编辑弹框样式 */
.create-workflow-form {
    padding: 20px 0;
}

.edit-steps-content {
    max-height: 400px;
    overflow-y: auto;
}

.edit-step {
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    margin-bottom: 16px;
    padding: 16px;
    background-color: #fafafa;
}

.service-name {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.step-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.audit-section {
    display: flex;
    align-items: center;
    gap: 12px;
}

.audit-label {
    font-weight: 500;
    color: #555;
    min-width: 60px;
}

.audit-options {
    display: flex;
    gap: 16px;
}

.remarks-section {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.remarks-label {
    font-weight: 500;
    color: #555;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

:deep(.el-table) {
    border-radius: 0;
}

:deep(.el-table th) {
    background-color: #fafafa;
}

:deep(.el-loading-mask) {
    border-radius: 0;
}
</style>